import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private long time ;
    private Runnable runnable;
    public MyTimerTask(Runnable runnable , long delay){
        this.runnable = runnable ;
        this.time = System.currentTimeMillis() + delay ;
    }
    public long getTime(){
        return time ;
    }
    public Runnable getRunnable(){
        return runnable;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}
class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();
    public void schedule(Runnable runnable , long delay){
        synchronized (locker){
            queue.offer(new MyTimerTask(runnable,delay));
            locker.notify() ;
        }
    }

    public MyTimer(){
        Thread scan = new Thread(()->{
            while(true){
                try{
                    synchronized(locker){
                        while (queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek() ;
                        long curTime = System.currentTimeMillis();
                        if(curTime >= task.getTime()){
                            task.getRunnable().run();
                            queue.poll();
                        }else{
                           locker.wait(task.getTime() - curTime );
                        }
                    }
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        } , "scan");
        scan.start();
    }

}


public class Test1 {
    public static void main(String[] args) {
         MyTimer timer = new MyTimer();
        Thread t1 = new Thread(()->{
            timer.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("1000ms 任务");
                }
            } , 1000);
          });
        Thread t2 = new Thread(()->{
            timer.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("2000ms 任务");
                }
            } , 2000);
        });
        Thread t3 = new Thread(()->{
            timer.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("3000ms 任务");
                }
            } , 3000);
        });
        t1.start();
        t2.start();
        t3.start();
        System.out.println("计时器开始");

    }
}
